package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.bo.FinishedHomeWorkBo;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.bo.QuestionBo;
import com.ruoyi.business.domain.vo.AnswersVo;
import com.ruoyi.business.domain.vo.CourseHomeWorkVo;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.domain.vo.ObjectiveAnswerVo;
import com.ruoyi.business.domain.vo.QuestionVo;
import com.ruoyi.business.domain.vo.UserVo;
import com.ruoyi.business.mapper.ChapterInfoMapper;
import com.ruoyi.business.mapper.ChapterQuestionMapper;
import com.ruoyi.business.mapper.ObjectiveAnswerMapper;
import com.ruoyi.business.mapper.QuestionMapper;
import com.ruoyi.business.question.QuestionHandle;
import com.ruoyi.business.question.QuestionHandleFactory;
import com.ruoyi.business.service.IQuestionService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 最爱喝兽奶
 * @create 2022/8/9
 **/
@SuppressWarnings("ALL")
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    private final Logger logger = LoggerFactory.getLogger(QuestionServiceImpl.class);

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private ChapterInfoMapper chapterInfoMapper;

    @Autowired
    private ObjectiveAnswerMapper objectiveAnswerMapper;

    @Autowired
    private ChapterQuestionMapper chapterQuestionMapper;

    @Autowired
    private THomeworkStuMapper homeworkStuMapper;

    @Autowired
    private THomeworkStuDetailMapper homeworkStuDetailMapper;

    @Autowired
    private TworkStuCommentMapper workStuCommentMapper;

    @Override
    @Transactional
    public void insertQuestionByCourseId(List<QuestionBo> boList, String courseId) {
        // 作业题型
        List<SysDictData> homeworkType = DictUtils.getDictCache("homework_type");
        for (QuestionBo questionBo : boList) {
            questionBo.setCourseId(courseId);
            insertQuestionByCourseId(questionBo);
        }
    }

    @Override
    public void insertQuestionByCourseId(QuestionBo bo) {
        // 作业题型
        List<SysDictData> homeworkType = DictUtils.getDictCache("homework_type");
        Question question = new Question();
        BeanUtils.copyBeanProp(question, bo, true);
        // 先判断当前题为何题型
        assert homeworkType != null;
        String typeValue = getDictValue(homeworkType, bo.getType());
        // 设置问题的题型
        question.setType(typeValue);
        // 设置问题的创建时间
        question.setCreateTime(new Date());
        // 设置问题的修改时间
        question.setUpdateTime(new Date());
        // 设置完题型之后先将问题插入至数据库中
        questionMapper.insert(question);
        // 根据问题的类型获取不同的问题处理器
        QuestionHandle questionHandle = QuestionHandleFactory.createQuestionHandle(typeValue);
        if (null == questionHandle) {
            logger.warn("请传入正确的题型");
            return;
        }
        question = questionHandle.insertAnswer(bo, question);
        questionMapper.updateById(question);
        if (StringUtils.isNotBlank(bo.getCourseId())) {
            // 设置问题的章节
            List<ChapterInfo> chapterInfos = chapterInfoMapper.selectList(new QueryWrapper<ChapterInfo>().eq("course_id", bo.getCourseId()));
            // 如果传入了章节id，就直接插入
            if (StringUtils.isNotBlank(bo.getChapterId())) {
                ChapterQuestion chapterQuestion = new ChapterQuestion();
                chapterQuestion.setChapterId(bo.getChapterId());
                chapterQuestion.setQuestionId(question.getId());
                chapterQuestion.setCourseId(bo.getCourseId());
                chapterQuestionMapper.insert(chapterQuestion);
                return;
            }
            // 如果没有传入章节id，就对比章节名，章节名匹配成功直接插入
            for (ChapterInfo chapterInfo : chapterInfos) {
                if (bo.getChapterName().equals(chapterInfo.getName())) {
                    ChapterQuestion chapterQuestion = new ChapterQuestion();
                    chapterQuestion.setChapterId(chapterInfo.getId());
                    chapterQuestion.setQuestionId(question.getId());
                    chapterQuestion.setCourseId(bo.getCourseId());
                    chapterQuestionMapper.insert(chapterQuestion);
                }
            }
        }

    }

    @Override
    public QuestionVo selectQuestionById(String id) {
        Question question = baseMapper.selectById(id);
        if (null == question) {
            throw new RuntimeException("请传入正确的id");
        }
        // 设置课程id，章节id
        // 根据问题的类型获得具体的处理器
        QuestionHandle questionHandle = QuestionHandleFactory.createQuestionHandle(question.getType());
        QuestionVo vo = questionHandle.queryResult(question);
        ChapterQuestion one = chapterQuestionMapper.selectOne(new QueryWrapper<ChapterQuestion>().eq("question_id", id));
        vo.setCourseId(one.getCourseId());
        vo.setChapterId(one.getChapterId());
        return vo;
    }

    @Transactional
    @Override
    public void updateQuestionByCourseId(QuestionBo bo) {
        // 将问题和答案信息删除，重新插入
        questionMapper.deleteById(bo.getId());
        // 将答案信息删除
        if (StringUtils.isNotBlank(bo.getId())) {
            objectiveAnswerMapper.delete(new QueryWrapper<ObjectiveAnswer>().eq("qid", bo.getId()));
        }
        // 删除题目和课程的映射信息
        if (StringUtils.isNotBlank(bo.getChapterId()) && StringUtils.isNotBlank(bo.getId())) {
            chapterQuestionMapper.delete(new QueryWrapper<ChapterQuestion>()
//                    .eq("chapter_id", bo.getChapterId())
                    .eq("question_id", bo.getId()));
        }
        insertQuestionByCourseId(bo);
    }

    @Override
    public TableDataInfo<QuestionVo> selectQuestionByPage(QuestionBo bo) {
        if (StringUtils.isNotBlank(bo.getContext())) {
            bo.setContext("%" + bo.getContext().trim() + "%");
        }
        Page<QuestionVo> page = baseMapper.queryPageList(PageUtils.buildPage(bo), bo);
        return PageUtils.buildTableDataInfo(page);
    }



    private LambdaQueryWrapper<Question> buildQueryWrapper(QuestionBo bo) {
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();

        return lqw;
    }

    private String getDictValue(List<SysDictData> homeworkType, String type) {
        for (SysDictData sysDictData : homeworkType) {
            if (sysDictData.getDictLabel().equals(type) || sysDictData.getDictValue().equals(type)) {
                return sysDictData.getDictValue();
            }
        }
        return null;
    }


    @Override
    public List<CourseHomeWorkVo> getHomeWorkByCourseIdNoAnswer(String courseId) {

        List<CourseHomeWorkVo> list = questionMapper.getHomeWorkByCourseIdNoAnswer(courseId);
        list.forEach(e ->{
           e = Transformer(e);

            List<String> stuAnswers = new ArrayList<>();
            e.setStuAnswers(stuAnswers) ;


        });
        return list;
    }

    @Override
    public Boolean submitCourseAnswers(List<CourseHomeWorkVo> vo,String courseId) {

        Boolean flag = true;
        String userId = SecurityUtils.getUserId();
        THomeworkStu t1 = new THomeworkStu();
        t1.setUploadUser(String.valueOf(userId));
        t1.setCourseId(courseId);
        //判断不可重复提交
        List<THomeworkStu> listHold = homeworkStuMapper.selectTHomeworkStuByCourseIdAndUid(t1);
        List<THomeworkStu> downList = listHold.stream().filter(e -> e.getFinished().equals("1")).collect(Collectors.toList());
        List<THomeworkStu> notYetList = listHold.stream().filter(e -> e.getFinished().equals("0")).collect(Collectors.toList());

        if (downList.size() >= 1) {
            throw new ServiceException("不能重复提交作业！");
        }
        if ( notYetList.size() == 0) {
            throw new ServiceException("教师尚未配置作业");
        }
        THomeworkStu t2 = notYetList.get(0);

        // 作业题型
        List<SysDictData> homeworkType = DictUtils.getDictCache("homework_type");



        //查询主表id
        String id = t2.getId();

        //副表插入N条
        vo.forEach(e -> {
            THomeworkStu homeworkStu2 = new THomeworkStu();
            homeworkStu2 = t2;
            THomeworkStuDetail homeworkStuDetail = new THomeworkStuDetail();
            homeworkStuDetail.setQid(String.valueOf(e.getQid()));
            homeworkStuDetail.setWorkId(String.valueOf(id));
            //主观题
            if("3".equals(e.getType()) && StringUtils.isNotNull(e.getStuSubAnswer())) {
                homeworkStuDetail.setStuAnswerSub(e.getStuSubAnswer());
            } else if ("1".equals(e.getType())) {
                if (StringUtils.isNotNull(e.getStuAnswers()) && StringUtils.isNotEmpty(e.getStuAnswers()) ) {
                    homeworkStuDetail.setStuAnswerObj(e.toString(e.getStuAnswers()));
                }
            } else {
                if(StringUtils.isNotNull(e.getStuAnswer())) {
                    homeworkStuDetail.setStuAnswerObj(e.getStuAnswer());
                }
            }
            homeworkStuDetail.setUploadUser(String.valueOf(SecurityUtils.getUserId()));
            int i1 = homeworkStuDetailMapper.insertTHomeworkStuDetail(homeworkStuDetail);

        });

        //把状态改为已完成
        t2.setFinished("1");
        t2.setFinishTime(DateUtils.getNowDate());
        homeworkStuMapper.updateTHomeworkStu(t2);

        //往互评主表差一条数据，等待被评
        TworkStuComment comment = new TworkStuComment();
        comment.setWorkId(String.valueOf(id));
        comment.setCourseId(courseId);
        comment.setUploadUser(String.valueOf(userId));
        comment.setUploadTime(DateUtils.getDate());
        comment.setFinished("0");
        workStuCommentMapper.insertTworkStuComment(comment);


        return flag;
    }


    @Override
    public List<CourseHomeWorkVo> getHomeWorkByCourseIdWithAnswer(FinishedHomeWorkBo bo) {

        List<CourseHomeWorkVo> list = questionMapper.getHomeWorkByCourseIdWithAnswer(bo);
        list.forEach(e ->{
            e = Transformer(e);
            if ("1".equals(e.getType())) {
                if (StringUtils.isNotNull(e.getStuAnswer())) {
                    List<String> str = Arrays.asList(e.getStuAnswer().split(","));
                    e.setStuAnswers(str);
                } else {
                    List<String> stuAnswers = new ArrayList<>();
                    e.setStuAnswers(stuAnswers) ;
                }
            }
        });
        return list;
    }

    @Override
    public void deleteQuestionById(String id) {
        // 根据id查询出题目的题型
        String type = baseMapper.selectTypeById(id);
        if (StringUtils.isBlank(type)) {
            throw new RuntimeException("请传入正确的题目id");
        }
        QuestionHandle questionHandle = QuestionHandleFactory.createQuestionHandle(type);
        questionHandle.deleteQuestion(id);
    }

    @Override
    public List<QuestionVo> selectQuestionsByIds(List<String> ids) {
        if (null != ids && ids.size() > 0) {
            List<QuestionVo> list = new ArrayList<>();
            for (String id : ids) {
                list.add(selectQuestionById(id));
            }
            return list;
        }
        return null;
    }

    public CourseHomeWorkVo Transformer(CourseHomeWorkVo vo) {
        List<AnswersVo> listContext = new ArrayList<>();
        if (StringUtils.isNotNull(vo.getObjContext())) {
            String[] objAnswers = vo.getObjContext().split(",");
            for (int i = 0; i <objAnswers.length ; i++) {

                AnswersVo vo1 = new AnswersVo();
                vo1.setId(objAnswers[i].substring(0,1));
                vo1.setContext(objAnswers[i].substring(1));
                listContext.add(vo1);
            }

            vo.setAnswers(listContext);
        }
        return vo;
    }
}
